<template>
  <div class="content">
    <el-dialog title="家长信息" :visible.sync="dialogParentVisible" width="800px" >
      <el-table
        :data="parent"
        border
        stripe
        style="width: 100%">
        <el-table-column
          prop="name"
          label="姓名"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="sex"
          label="性别"
          sortable
        >
          <template slot-scope="scope">
            <span v-if="scope.row.sex===1">男</span>
            <span v-else>女</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="tel"
          label="电话"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="relation"
          label="关系">
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      title="导入新同学"
      :visible.sync="dialogVisible"
      width="800px"
      @close="closeDialog2"
    >
      <el-form  style="width: 100%" label-width="150px" :inline="true">
<!--        style="width:100%;position: relative;margin-left: 50%;left: -130px"-->
        <el-form-item label="班级" prop="classId" >
          <el-select v-model="classId" placeholder="请选择班级" filterable @change="getStudentNum">
            <template v-for="item in classList">
              <el-option :label="item.grade.year+item.grade.name+item.name" :value="item.id"></el-option>
            </template>
          </el-select>
          <p>当前班级的人数为：<em>{{this.studentNum}}</em></p>
        </el-form-item >
        <el-form-item label="设置开始排序数">
          <el-input type="number" v-model="startNum"></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 50%;position: relative;left: -110px">

          <el-upload
            ref="upload2"
            class="upload-demo"
            accept=".xlsx,.xls"
            :auto-upload="false"
            action=""
            :limit="1"
            :on-exceed="handleExceed"
            :http-request="httpRequest"
          >
            <template #trigger>
              <el-tooltip content="仅限文件格式为.xls、.xlsx" placement="top" effect="light">

                <el-button type="primary">选择文件</el-button>
              </el-tooltip>
            </template>
            <el-button
              style="margin-left: 10px"
              type="success"
              @click="submitUpload"
              :loading="loadingBtn"
            >立即导入<i class="el-icon-upload el-icon-right"></i>
            </el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <el-alert title="此操作将新名单分配到指定的班级且自动生成对应的学号和账号" type="warning" close-text="知道了" show-icon
                style="line-height: 12px;"></el-alert>
      <el-alert title="开始排序数指批量导入时班级排序号的开始数，系统将自动递增，请根据班级人数来填选" type="warning" close-text="知道了" show-icon
                style="line-height: 12px;"></el-alert>
      <el-alert title="上传字段依次为姓名、性别（男/女）、身份证，注：表格第一行默认不识别，可填字段名" type="warning" close-text="知道了" show-icon
                style="line-height: 12px;"></el-alert>
    </el-dialog>

    <el-dialog title="学生管理" :visible.sync="dialogSaveVisible" width="500px" @close="closeDialog" >
      <el-form  :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm" style="width: 100%">
        <el-form-item label="名字" prop="name"  >
          <el-input v-model="form.name" style="width: 300px" placeholder="如：张三"></el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard"  >
          <el-input v-model="form.idCard" style="width: 300px" placeholder="如：41111XXXXXXX" ></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" placeholder="请选择班级" filterable>
            <template v-for="item in classList">
              <el-option :label="item.grade.year+item.grade.name+item.name" :value="item.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="学号" prop="schoolno"  v-if="this.form.id!=null">
          <el-input v-model="form.schoolno" style="width: 300px" type="number" :disabled="this.form.id==null?false:true"></el-input>
        </el-form-item>
        <el-form-item label="班级排序号" prop="schoolno" v-else>
          <el-input v-model="form.schoolno" style="width: 300px" type="number"></el-input>
          <el-alert title="如：04，将会根据所选的班级生成对应的学号" type="info"
                    style="line-height: 12px;"></el-alert>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="form.tel" style="width: 300px" type="number"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" style="width: 300px" ></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" style="width: 300px" ></el-input>
        </el-form-item>
        <el-form-item label="照片" prop="photo">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            action="http://localhost:8085/files/upload"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.photo" :src="form.photo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleUpdate(form)" v-if="this.form.id">更新</el-button>
          <el-button type="primary" @click="handleSave(form)" v-else>添加</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-form :inline="true"  class="demo-form-inline" >
      <el-form-item>
        <el-input  placeholder="学号" v-model="search.schoolno"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input  placeholder="姓名" v-model="search.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button  @click="getList">搜索</el-button>
      </el-form-item>
      <el-form-item >
        <el-form-item >
          <el-popconfirm title="这是确定批量删除吗？" @onConfirm="handleDel(null)">
            <template #reference>
              <el-button type="danger" slot="reference" :disabled="delBtlStatu" >批量删除</el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form-item>
      <el-form-item >
        <el-button  @click="dialogSaveVisible = true" type="primary">新添单条同学</el-button>
      </el-form-item>
      <el-form-item >
        <el-button  @click="dialogVisible = true" type="primary">Execl导入新同学</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="table"
      ref="multipleTable"
      tooltip-effect="light"
      style="width: 100%;font-size: 10px"
      sroll
      border
      stripe
      @row-click="toggleSelection"
      @selection-change="handleSelectionChange"
      v-loading="loading"
      element-loading-text="拼命加载中..."
      element-loading-background="rgba(255, 255, 255, 0.7)">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column
        label="照片"
      >
        <template slot-scope="scope">

          <el-avatar shape="square" v-if="scope.row.photo==null||scope.row.photo===''" size="medium" :src="squareUrl"></el-avatar>
          <el-avatar shape="square" v-else size="medium" :src="scope.row.photo"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column
        prop="schoolno"
        label="学号">
      </el-table-column>
      <el-table-column
        prop="name"
        label="名字">
      </el-table-column>
      <el-table-column
        prop="idCard"
        label="身份证"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="classId"
        label="班级"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{scope.row.className}}
        </template>
      </el-table-column>
      <el-table-column
        label="性别">
        <template slot-scope="scope">
          <p v-if="scope.row.sex===1">男</p>
          <p v-else>女</p>
        </template>
      </el-table-column>
      <el-table-column
        prop="birthday"
        label="生日">
      </el-table-column>
      <el-table-column
        prop="tel"
        label="电话"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        fixed="right">
        <template slot-scope="scope">
          <el-button  type="text" size="small" @click="handelGetParent(scope.row.id)">查看家长信息</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button  type="text" size="small" @click="handelEdit(scope.row)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="这是确定删除吗？" @onConfirm="handleDel(scope.row.id)">
            <el-button  type="text" slot="reference" size="small">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="current"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
import { getClassList, getList, save, update, del, importStudent, getParentInfo } from '@/api/sysUser/student'

export default {
  name: "Student",
  data() {
    return {
      //按钮状态
      loadingBtn: false,
      //头像
      squareUrl:"https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
      loading: true,
      //批量删除
      delBtlStatu: true,
      dialogVisible: false,
      dialogSaveVisible: false,
      dialogParentVisible: false,
      // 分页用到的属性
      total: 0,
      current: 1,
      size: 10,
      //表格数据
      table:[],
      //搜索
      search:{
        schoolno:"",
        name:"",
      },
      //表单
      form:{
        id:null,
        name:"",
        idCard: "",
        schoolno:"",
        classId:"",
        sex:"",
        tel:"",
        email:"",
        birthday:"",
        address:"",
        photo:"",
      },
      //班级
      options:[],
      //校验
      rules: {
        name: [
          { required: true, message: '请输入名字', trigger: 'blur' },
        ],
        idCard: [
          { required: true, message: '请输入身份证', trigger: 'blur' },
          { min: 18, max: 18, message: '长度在 18 个字符', trigger: 'blur' }
        ],
        schoolno: [
          { required: true, message: '请输入班级排序号', trigger: 'blur' },
        ],
        classId: [
          { required: true, message: '请选择班级', trigger: 'change' }
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
      },
      // 根据多选的数量，将其批量按钮可用/不可用进行变化
      multipleSelection: [],

      //班级的显示
      classList:[],
      //批量上传学生
      classId:'',
      //上传开始数
      startNum: 1,
      studentNum:'',
      //家长信息
      parent:[],


    }
  },
  created() {
    this.getList()
    this.getClassList()
  },
  methods: {
    toggleSelection(row) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    // 触发事件为有复选框发生变化，会传递所有勾选的行数据对象数组
    handleSelectionChange(val) {
      this.multipleSelection = val;
      //设置批量删除的按钮的可用/不可用
      this.delBtlStatu = val.length == 0
    },
    //这里是分页
    handleSizeChange(val) {
      this.size = val
      this.getList()
      this.getClassList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getList()
      this.getClassList()
    },
    getList(){
      getList(this.search.schoolno,this.search.name,this.current,this.size).then(res => {
        this.table = res.data.data.records
        this.size = res.data.data.size
        this.total = res.data.data.total
        this.current = res.data.data.current
        this.loading = false

      })
    },
    //上传
    handleAvatarSuccess(res, file) {
      this.form.photo = res.data
      // this.form.photo = URL.createObjectURL(file.raw);
      this.$message({
        message:"已上传成功",
        type:"success"
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //关闭对话框
    closeDialog(){
      this.form= { name:"", idCard: "", class:"", sex:"", tel:"", email:"", birthday:"", address:"", photo:"",}
      this.$refs.form.resetFields();
      this.dialogSaveVisible = false
      this.$refs.upload.clearFiles()  //清空文件
    },
    closeDialog2(){
      this.$refs.upload2.clearFiles()
      this.classId=""
      this.startNum=1
      this.studentNum=""
    },
    //显示所有班级
    getClassList(){
      getClassList().then(res => {
        this.classList = res.data.data
      })
    },
    //添加学生
    handleSave(){
      this.$refs.form.validate(valid => {
        if (valid) {
          save(this.form).then(res => {
            this.dialogSaveVisible = false
            this.getList()
            this.$message({
              message:res.data.msg,
              type:"success"
            })
            this.getList()
            this.getClassList()
          })
        } else {
          return false;
        }
      });
    },
    handelEdit(row){
      this.dialogSaveVisible = true
      this.$nextTick(() => {
        this.form = JSON.parse(JSON.stringify(row))
      })
    },
    handleUpdate(){
      this.$refs.form.validate(valid => {
        if (valid) {
          update(this.form).then(res=>{
            this.dialogSaveVisible = false
            this.$message({
              message: res.data.msg,
              type: 'success'
            })
            this.getList()
            this.getClassList()
          })
        } else {
          return false;
        }
      });
    },
    handleDel(id){
      const ids = []
      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }

      del(ids).then(res => {
        this.$message({
          message: res.data.msg,
          type: 'success'
        });
        this.getList()
        this.getClassList()
      })
    },
    //批量导入学生
    handleExceed(files, fileList) {
      this.$message.warning('每次导入只能选择一个文件');
    },
    //如果把提交函数用在http-request钩子中，fileList多长就执行请求多少次接口，依旧是无法做到只请求一次上传多文件
    httpRequest(param) {
        if (this.classId==null||this.classId==="") {
          this.$message({
            message: '请选择班级',
            type: 'error',
          });
        } else {

          let excelFileObj = param.file
          let form = new FormData()// FormData 对象
          form.set('excel', excelFileObj)// 文件对象
          // console.log(form)
          // console.log(this.classId)
          this.loadingBtn = true
          importStudent(this.classId,this.startNum,form).then(res => {
            this.$message({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
            });
            this.loadingBtn = false
            this.dialogVisible = false
            this.getList()
            this.getClassList()
            this.$refs.upload2.clearFiles()
          })
        }

    },
    submitUpload() {
      this.$refs.upload2.submit()
    },
    //获取班级人数
    getStudentNum(){
      for(var i = 0; i < (this.classList).length;i ++){
        if (this.classList[i].id == this.classId){
          this.studentNum = this.classList[i].studentNum
        }
      }
    },
    handelGetParent(id){
      getParentInfo(id).then(res => {
        this.parent = res.data.data
        this.dialogParentVisible = true
      })
    }

  },
}
</script>

<style >
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
